import 'package:tile/tile.dart';

extension IntExt on int {
  String toStr(int num) {
    if (this < 0 || this > 19) {
      // throw Exception("num必须大于等于0，小于等于19");
    }
    if (this < 10) {
      return "0$this";
    }
    return "$this";
  }
}

extension Ext on Board {
  String get allStep {
    String steps = "";
    currNode.backStepList().forEach((element) {
      // [3,4] => +1704
      steps += element.bw == Board.BLACK ? "+" : "-";
      steps += element.x == 0
          ? element.x.toStr(2)
          : (getBoardSize() - element.x + 1).toStr(2);
      steps += element.y.toStr(2);
    });
    return steps;
  }

  void showYzSteps(String steps,
      {bool refreshUI = true, bool forceChess = true}) {
    if (steps.length % 5 != 0) {
      throw Exception("错误的棋谱：$steps");
    }
    int num = steps.length ~/ 5;

    SgfNode node = currNode;

    for (int i = 0; i < num; i++) {
      final step = steps.substring(i * 5, i * 5 + 5);

      int bw = step.substring(0, 1) == "+" ? Board.BLACK : Board.WHITE;
      int x = 0;
      int y = 0;
      if (!step.contains('0000')) {
        x = getBoardSize() - int.parse(step.substring(1, 3)) + 1;
        y = int.parse(step.substring(3, 5));
      }

      nextColor = bw;
      node = node.addChild(SgfNode.fromXY(x, y, bw)..markOrderState(1));
    }
    showSgfNode(node);
    if (refreshUI) {
      postEvent('showYzSteps');
    }
  }

  bool put(int x, int y) {
    return putNode(SgfNode.fromXY(x, y, nextColor));
  }
}
